/*
 * Copyright (C) 2017 Pingan, Inc. All Rights Reserved.
 */

package com.pingan.haofang.searchcloud.api.facade.impl;

import com.pingan.haofang.searchcloud.api.IndexDataPacket;
import com.pingan.haofang.searchcloud.api.IndexDataPushService;
import com.pingan.haofang.searchcloud.api.StorageCluster;
import com.pingan.haofang.searchcloud.api.constants.EngineType;
import com.pingan.haofang.searchcloud.api.facade.IndexDataPushFacade;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 数据索引逻辑
 *
 * @author zhangbi617
 * @date 2017-07-17
 */
@Service
public class IndexDataPushFacadeImpl implements IndexDataPushFacade, ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    private Map<EngineType, IndexDataPushService> serviceMap = new HashMap<>();

    @Override
    public boolean repository(StorageCluster storageCluster, IndexDataPacket indexDataPacket,
                              int millisecondTimeOut, boolean needRoute) {
        return serviceMap.get(storageCluster.getEngineType())
                .repository(storageCluster.getClusterHost(), indexDataPacket, millisecondTimeOut, needRoute);
    }

    @Override
    public Long getMaxValue(StorageCluster storageCluster, String indexName, String fieldName) {
        return serviceMap.get(storageCluster.getEngineType()).getMaxValue(storageCluster.getClusterHost(), indexName, fieldName);
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, IndexDataPushService> map = applicationContext.getBeansOfType(IndexDataPushService.class);
        for (IndexDataPushService service : map.values()) {
            serviceMap.put(service.getEngineType(), service);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
